package com.toprs.business.service

import cn.afterturn.easypoi.excel.ExcelExportUtil
import cn.afterturn.easypoi.excel.entity.TemplateExportParams
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.toprs.base.exception.CustomException
import com.toprs.business.entity.AppReport
import com.toprs.business.entity.ApplicationBase
import com.toprs.business.mapper.*
import com.toprs.business.query.ReportQuery
import jakarta.servlet.http.HttpServletResponse
import org.springframework.core.io.ClassPathResource
import org.springframework.stereotype.Service
import java.math.BigDecimal
import java.text.SimpleDateFormat
import java.util.Date
import java.util.HashMap

@Service
class ReportService(val appMapper: ApplicationBaseMapper, val appReportMapper: AppReportMapper) {

    fun addReport(report: AppReport) {

        val app = appMapper.selectByPrimaryKey(report.appId!!) ?: throw CustomException("申请单不存在！")

        if (app.currentUser!! != "-1") throw CustomException("当前申请未办结！")

        val reportTime = Date()
        report.reportTime = reportTime

        appMapper.update {
            set(ApplicationBaseDynamicSqlSupport.bxAmount) equalTo report.bxje!!
            set(ApplicationBaseDynamicSqlSupport.reportTime) equalTo reportTime
            where { ApplicationBaseDynamicSqlSupport.id isEqualTo report.appId!! }
        }

        val appReport = appReportMapper.selectByPrimaryKey(report.appId!!)
        if (appReport == null) {
            appReportMapper.insert(report)
        } else {
            appReportMapper.updateByPrimaryKey(report)
        }
    }

    fun queryReport(reportQuery: ReportQuery): List<ApplicationBase> {
        val list = appMapper.queryReport(reportQuery).toMutableList()

        if (reportQuery.ifReport == 1) {
            val sum = ApplicationBase()
            sum.bxAmount = BigDecimal(0.00)
            sum.winePrice = BigDecimal(0.00)
            sum.catePrice = BigDecimal(0.00)
            sum.stayPrice = BigDecimal(0.00)
            sum.otherPrice = BigDecimal(0.00)
            sum.cast = BigDecimal(0.00)
            list.map {
                sum.bxAmount = sum.bxAmount!!.add(it.bxAmount)
                sum.winePrice = sum.winePrice!!.add(it.winePrice ?: BigDecimal(0))
                sum.catePrice = sum.catePrice!!.add(it.catePrice ?: BigDecimal(0))
                sum.stayPrice = sum.stayPrice!!.add(it.stayPrice ?: BigDecimal(0))
                sum.otherPrice = sum.otherPrice!!.add(it.otherPrice ?: BigDecimal(0))
                sum.cast = sum.cast!!.add(it.cast ?: BigDecimal(0))
            }
//            sum.wineReport = null
            list.add(sum)
        }
        return list
    }

    private val timeFormat = SimpleDateFormat("YYYY-MM-dd HH:mm:ss")
    private val dateFormat = SimpleDateFormat("YYYY-MM-dd")
    private val wineType = listOf("定制", "青龙", "啤酒", "其他")


    fun exportExcelItems(list: List<ApplicationBase>, response: HttpServletResponse) {

        val jsonList = JSON.parseArray(JSONObject.toJSONString(list), JSONObject::class.java)

        for (json in jsonList) {
            json["applyDate"] = if (json["applyDate"] != null) dateFormat.format(json["applyDate"]) else ""
            json["createTime"] = if (json["createTime"] != null) timeFormat.format(json["createTime"]) else ""
            json["updateTime"] = if (json["updateTime"] != null) timeFormat.format(json["updateTime"]) else ""
            json["useTime"] = if (json["useTime"] != null) timeFormat.format(json["useTime"]) else ""
            json["reportTime"] = if (json["reportTime"] != null) timeFormat.format(json["reportTime"]) else ""
            json["wineReport"] = if (json["wineReport"] == null) "" else if (json["wineReport"] == 0) "否" else "是"
            json["wineType"] = if (json["wineType"] == null) "" else wineType[json["wineType"] as Int]
        }


        val inputStream = ClassPathResource("template2.xlsx").inputStream
        val params = TemplateExportParams(inputStream)
        val map: MutableMap<String, Any> = HashMap()

        map["maplist"] = jsonList
        map["title"] = "title"
        val workbook = ExcelExportUtil.exportExcel(params, map)

        response.contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        response.characterEncoding = "UTF-8"
        val os = response.outputStream
        workbook.write(os)
        os.flush()
        os.close()
    }


    fun exportExcel(reportQuery: ReportQuery, response: HttpServletResponse) {
        exportExcelItems(queryReport(reportQuery), response)
    }
}